package cn.xiaye.httpserver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import cn.xiaye.httpserver.Request;
import cn.xiaye.httpserver.action.DefaultListAction;

/**
 * 多线程Socket
 * 
 * @author 王夏夜
 * 
 */
public class ThreadSocket extends Thread {
	public static final int POST_MAX_LENTH = 4500;
	Socket sock = null;
	byte[] buf = null;

	/**
	 * 构造一个多线程Socket
	 * 
	 * @param sock
	 *            服务员
	 */
	public ThreadSocket(Socket sock) {
		this.sock = sock;
	}

	public void run() {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			InputStream is = sock.getInputStream();
			byte[] buffer = new byte[1024];
			int size = -1;
			while ((size = is.read(buffer)) != -1) {
				bos.write(buffer, 0, size);
				if (is.available() == 0) {
					Thread.sleep(5);
					if(is.available()==0){
						break;
					}
				}
			}
			buf = bos.toByteArray();
			String inputStr = new String(buf);
			/** 根据客户端请求数据 调用DefaultListAction */
			Request request = new Request(inputStr);
			Response response = new Response(sock);

			DefaultListAction.doService(request, response);

			response.flushResponse();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				sock.getOutputStream().flush();
				sock.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
